// @ts-ignore
import { ref, reactive } from 'vue'
// @ts-ignore
import { ElMessage } from 'element-plus'
// @ts-ignore
import * as systemApi from '../api/system'
// @ts-ignore
import type { Role, RoleQueryParams } from '../api/system'

// @ts-ignore
export const useRoleManagement = () => {
  // 角色管理相关的响应式数据
  // @ts-ignore
  const loading = ref(false)
  // @ts-ignore
  const saving = ref(false)
  // @ts-ignore
  const selectedRoles = ref([])
  // @ts-ignore
  const tableData = ref([])
  // @ts-ignore
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0
  })

  // 表单数据
  // @ts-ignore
  const editingRole = ref({
    id: 0,
    name: '',
    description: '',
    permissions: []
  })

  // @ts-ignore
  const detailRole = ref({
    id: 0,
    name: '',
    description: '',
    permissions: [],
    createdAt: '',
    updatedAt: ''
  })

  // 查询参数
  // @ts-ignore
  const queryParams = reactive({
    page: 1,
    limit: 20,
    name: ''
  })

  // 加载角色列表
  // @ts-ignore
  const loadRoles = async () => {
    // @ts-ignore
    loading.value = true
    try {
      const params: RoleQueryParams = {
        page: pagination.page,
        limit: pagination.limit,
        name: queryParams.name
      }
      
      const response = await systemApi.getRoles(params)
      
      if (response.data && response.data.list) {
        // @ts-ignore
        tableData.value = response.data.list
        // @ts-ignore
        pagination.total = response.data.pagination.total
      }
    } catch (error: any) {
      console.error('加载角色数据失败:', error)
      ElMessage.error('加载角色数据失败: ' + (error.message || '未知错误'))
    } finally {
      // @ts-ignore
      loading.value = false
    }
  }

  // 搜索角色
  // @ts-ignore
  const handleSearch = () => {
    // @ts-ignore
    pagination.page = 1
    loadRoles()
  }

  // 重置搜索条件
  // @ts-ignore
  const handleReset = () => {
    Object.assign(queryParams, {
      page: 1,
      limit: 20,
      name: ''
    })
    loadRoles()
  }

  // 处理选择变化
  // @ts-ignore
  const handleSelectionChange = (selection: any[]) => {
    // @ts-ignore
    selectedRoles.value = selection
  }

  // 显示角色详情
  // @ts-ignore
  const showRoleDetail = async (role: any) => {
    try {
      const response = await systemApi.getRole(role.id)
      if (response.data) {
        // @ts-ignore
        detailRole.value = response.data
        // @ts-ignore
        return detailRole.value
      }
    } catch (error: any) {
      ElMessage.error('获取角色详情失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 编辑角色
  // @ts-ignore
  const editRole = async (role: any) => {
    try {
      const response = await systemApi.getRole(role.id)
      if (response.data) {
        // @ts-ignore
        editingRole.value = { ...response.data }
        // @ts-ignore
        return editingRole.value
      }
    } catch (error: any) {
      ElMessage.error('获取角色信息失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 保存角色（创建或更新）
  // @ts-ignore
  const saveRole = async () => {
    try {
      // @ts-ignore
      saving.value = true
      
      if (editingRole.value.id) {
        // 更新角色
        await systemApi.updateRole(editingRole.value.id, {
          name: editingRole.value.name,
          description: editingRole.value.description,
          permissions: editingRole.value.permissions
        })
        ElMessage.success('角色更新成功')
      } else {
        // 创建角色
        await systemApi.createRole({
          name: editingRole.value.name,
          description: editingRole.value.description,
          permissions: editingRole.value.permissions
        })
        ElMessage.success('角色创建成功')
      }
      
      loadRoles()
      return true
    } catch (error: any) {
      ElMessage.error('操作失败: ' + (error.message || '未知错误'))
      throw error
    } finally {
      // @ts-ignore
      saving.value = false
    }
  }

  // 删除角色
  // @ts-ignore
  const deleteRole = async (role: any) => {
    try {
      await systemApi.deleteRole(role.id)
      ElMessage.success('删除成功')
      loadRoles()
      return true
    } catch (error: any) {
      ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      throw error
    }
  }

  // 分页相关方法
  // @ts-ignore
  const handleSizeChange = (val: number) => {
    // @ts-ignore
    pagination.limit = val
    // @ts-ignore
    pagination.page = 1
    loadRoles()
  }

  // @ts-ignore
  const handleCurrentChange = (val: number) => {
    // @ts-ignore
    pagination.page = val
    loadRoles()
  }

  return {
    // 数据
    // @ts-ignore
    loading,
    // @ts-ignore
    saving,
    // @ts-ignore
    selectedRoles,
    // @ts-ignore
    tableData,
    // @ts-ignore
    pagination,
    // @ts-ignore
    editingRole,
    // @ts-ignore
    detailRole,
    // @ts-ignore
    queryParams,
    
    // 方法
    // @ts-ignore
    loadRoles,
    // @ts-ignore
    handleSearch,
    // @ts-ignore
    handleReset,
    // @ts-ignore
    handleSelectionChange,
    // @ts-ignore
    showRoleDetail,
    // @ts-ignore
    editRole,
    // @ts-ignore
    saveRole,
    // @ts-ignore
    deleteRole,
    // @ts-ignore
    handleSizeChange,
    // @ts-ignore
    handleCurrentChange
  }
}